package com.zx.sercurity.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;

public class BootloaderUtils {

    private static final String TAG = "BootloaderUtils";

    /**
     * 检查是否 Bootloader 解锁（多种方式）
     */
    public static boolean isBootloaderUnlocked() {
        String verifiedBootState = getSystemProperty("ro.boot.verifiedbootstate", "");
        if ("orange".equalsIgnoreCase(verifiedBootState)) {
            Log.d(TAG, "verifiedbootstate = orange");
            return true;
        }

        String flashLocked = getSystemProperty("ro.boot.flash.locked", "1");
        if ("0".equals(flashLocked)) {
            Log.d(TAG, "flash_locked = 0");
            return true;
        }

        String unlockType = getSystemProperty("ro.boot.unlocked", "0");
        if ("1".equals(unlockType)) {
            Log.d(TAG, "ro.boot.unlocked = 1");
            return true;
        }

        // 部分设备（如华为）从 /proc/cmdline 中解析
        String cmdline = readCmdline();
        if (cmdline.contains("androidboot.verifiedbootstate=orange")) {
            Log.d(TAG, "cmdline contains orange state");
            return true;
        }

        return false;
    }

    /**
     * 获取系统属性
     */
    private static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> systemProperties = Class.forName("android.os.SystemProperties");
            return (String) systemProperties.getMethod("get", String.class, String.class)
                    .invoke(null, key, defaultValue);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 读取 /proc/cmdline 内容
     */
    private static String readCmdline() {
        try (BufferedReader br = new BufferedReader(new FileReader("/proc/cmdline"))) {
            return br.readLine();
        } catch (Exception e) {
            return "";
        }
    }
}

